package com.yuki.weather;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.bumptech.glide.Glide;
import com.yuki.weather.data.AirQualityData;
import com.yuki.weather.data.DailyForecast;
import com.yuki.weather.data.WeatherForecast;
import com.yuki.weather.data.WeatherNow;
import com.yuki.weather.util.WeatherApiUtils;

import java.util.List;

public class WeatherActivity extends AppCompatActivity {
    TextView tvCity, tvUpdateTime, tvTemp, tvWeatherInfo;
    ImageView ivCond;
    TextView tvAqi, tvPm25;
    String weatherId = "CN101211101";
    SwipeRefreshLayout swipeRefreshLayout;
    LinearLayout forecastLayout;
    public static final int CITY_REQ_CODE = 0;
    private static final String KEY_WEATHER_ID = "weather_id";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);
        loadWeatherId();
        updateData();
        tvAqi = findViewById(R.id.aqi_text);
        tvPm25 = findViewById(R.id.pm25_text);
        forecastLayout = (LinearLayout) findViewById(R.id.forecast_layout);
        tvCity = findViewById(R.id.title_city_tv);
        tvUpdateTime = findViewById(R.id.title_pub_time_tv);
        tvTemp = findViewById(R.id.now_temp_tv);
        tvWeatherInfo = findViewById(R.id.now_cond_tv);
        ivCond = findViewById(R.id.now_cond_iv);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                updateData();
            }
        });
        tvCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(WeatherActivity.this, SelectCityActivity.class);
                startActivityForResult(i, CITY_REQ_CODE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CITY_REQ_CODE && resultCode == Activity.RESULT_OK) {
            weatherId = SelectCityActivity.getWeatherIdByIntent(data);
            updateData();
            saveWeatherId();
        }
    }

    private void updateWeatherNow() {
        WeatherApiUtils.getWeatherNow(this, weatherId, new WeatherApiUtils.OnWeatherNowFinished() {
            @Override
            public void onFinished(WeatherNow data) {
                if (data != null) {
                    tvCity.setText(data.basic.location);
                    tvUpdateTime.setText(data.update.loc);
                    tvTemp.setText(data.now.tmp);
                    tvWeatherInfo.setText(data.now.cond_txt);
                    updateWeatherIcon(data.now.cond_code, ivCond);
                }
            }
        });
    }

    private void updateWeatherIcon(String cond_code, ImageView ivCond) {
        String url = String.format("https://cdn.heweather.com/cond_icon/%s.png", cond_code);
        Glide.with(this).load(Uri.parse(url)).into(ivCond);
    }

    private void updateWeatherForecast() {
        WeatherApiUtils.getWeatherForecast(this, weatherId, new WeatherApiUtils.OnWeatherForecastFinished() {
            @Override
            public void onFinished(WeatherForecast data) {
                if (data != null) {
                    forecastLayout.removeAllViews();
                    List<DailyForecast> forecastList = data.dailyForecastList;
                    for (int i = 0; i < forecastList.size(); i++) {
                        DailyForecast f = forecastList.get(i);
                        View v = LayoutInflater.from(WeatherActivity.this).inflate(R.layout.forecast_item, null, false);
                        TextView itemDateText = v.findViewById(R.id.item_date_text);
                        TextView itemMaxText = v.findViewById(R.id.item_max_text);
                        TextView itemMinText = v.findViewById(R.id.item_min_text);
                        ImageView itemIvDayCon = v.findViewById(R.id.item_iv_day_con);
                        ImageView itemIvNightCon = v.findViewById(R.id.item_iv_night_con);
                        itemDateText.setText(f.date);
                        itemMaxText.setText(f.tmp_max + "℃");
                        itemMaxText.setText(f.tmp_min + "℃");
                        updateWeatherIcon(f.cond_code_d, itemIvDayCon);
                        updateWeatherIcon(f.cond_code_n, itemIvNightCon);
                        forecastLayout.addView(v);
                    }
                }
            }
        });
    }

    private void upDateWeatherAqi() {
        WeatherApiUtils.getAirQualityData(this, weatherId, new WeatherApiUtils.OnAirQualityFinished() {
            @Override
            public void onFinished(AirQualityData data) {
                swipeRefreshLayout.setRefreshing(false);
                if (data != null && data.status.equalsIgnoreCase("ok")) {
                    tvAqi.setText(data.airNowCity.aqi);
                    tvPm25.setText(data.airNowCity.pm25);
                } else {
                    tvAqi.setText("--");
                    tvPm25.setText("--");
                }
            }
        });
    }

    private void updateData() {
        updateWeatherNow();
        updateWeatherForecast();
        upDateWeatherAqi();
    }

    private void loadWeatherId() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        weatherId = sharedPreferences.getString(KEY_WEATHER_ID, "CN101210701");
    }

    private void saveWeatherId() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(KEY_WEATHER_ID,weatherId);
        editor.apply();
    }

}
